package com.atguigu.mq.simple;

import com.rabbitmq.client.*;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

public class Consumer {
    public static void main(String[] args) throws IOException, TimeoutException {
        //获取链接工厂，初始化连接参数
        ConnectionFactory connectionFactory = new ConnectionFactory();
        //主机地址
        connectionFactory.setHost("192.168.164.128");
        //链接端口，默认为5672
        connectionFactory.setPort(5672);
        //连接虚拟主机；默认为/
        connectionFactory.setVirtualHost("/");
        //连接用户名，默认为admin
        connectionFactory.setUsername("admin");
        //连接用户密码
        connectionFactory.setPassword("admin");
        //创建连接
        Connection connection = connectionFactory.newConnection();

        //通过connection获取信道
        Channel channel = connection.createChannel();
        //声明队列
        String queue = "simple_queue";
        channel.queueDeclare(queue,true,false,false,null);

        DefaultConsumer defaultConsumer = new DefaultConsumer(channel){
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {

                System.out.println("consumerTag:"+consumerTag);
                System.out.println("Exchange:"+envelope.getExchange());
                System.out.println("RoutingKey:"+envelope.getRoutingKey());
                System.out.println("properties:"+properties);
                System.out.println("body:"+new String(body));
            }
        };

        // 消费者类似一个监听程序,主要是用来监听消息,客户端自动签收
        channel.basicConsume("simple_queue",true,defaultConsumer);

    }
}
